package com.wr.ForkJoinDemo11;

import java.util.concurrent.RecursiveTask;

/**
 * 如何使用ForkJoin
 * 1、使用ForkJoinPool来执行
 * 2、计算任务ForkJoinPool。execute（ForkJoinTask task）
 * 3、计算类要继承RecursiveTask类，并实现计算方法
 */
public class ForkJoinDemo11 extends RecursiveTask<Long> {
    private Long start;
    private Long end;
    // 临界值
    private Long temp = 10000L;

    public ForkJoinDemo11(Long start, Long end) {
        this.start = start;
        this.end = end;
    }


    @Override
    protected Long compute() {
        if (end-start<temp){
            // 正常计算
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }else {
            // ForkJoin
            long middle = (start + end) / 2;  // 1/4
            ForkJoinDemo11 task1 = new ForkJoinDemo11(start, middle);
            task1.fork();  // 拆分任务，把任务压入线程队列
            ForkJoinDemo11 task2 = new ForkJoinDemo11(middle+1, end);
            task2.fork();  // 拆分任务，把任务压入线程队列
            // 合并结果
            return task1.join() +task2.join();
        }
    }
}
